package com.zhouxin.customview.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.zhouxin.customview.R
import com.zhouxin.customview.extensions.dp2px

/**
 * Copyright©
 * FileName: AvatarView
 * Author: ZhouXin
 * Date: 2022/6/7
 * Description:Xfermode学习
 */
private val IMAGE_WIDTH = 200f.dp2px
private val IMAGE_PADDING = 20f.dp2px
private val XFERMODE = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

class AvatarView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val bounds = RectF(
        IMAGE_PADDING,
        IMAGE_PADDING,
        IMAGE_PADDING + IMAGE_WIDTH,
        IMAGE_PADDING + IMAGE_WIDTH
    )

    override fun onDraw(canvas: Canvas) {
        //取出离屏缓冲区域（应该尽可能的小，因为离屏缓冲比较耗资源，性能比较差）
        val count = canvas.saveLayer(bounds, null)
        canvas.drawOval(
            IMAGE_PADDING,
            IMAGE_PADDING,
            IMAGE_PADDING + IMAGE_WIDTH,
            IMAGE_PADDING + IMAGE_WIDTH,
            paint
        )
        paint.xfermode = XFERMODE
        canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
        paint.xfermode = null
        //将离屏缓冲区域放回去
        canvas.restoreToCount(count)
    }

    /**
     * 根据输入尺寸获取bitmap
     */
    private fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        //只测量图片尺寸
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.drawable.fire_bg, options)
        options.inJustDecodeBounds = false
        //原图多大
        options.inDensity = options.outWidth
        //目标多大
        options.inTargetDensity = width
        //得到的bitmap就会根据options.inDensity和options.inTargetDensity的比例缩放至需要的大小，优化了图片的加载
        return BitmapFactory.decodeResource(resources, R.drawable.fire_bg, options)
    }
}